package com.chinasoft.reposearch.controller;

import com.chinasoft.reposearch.entity.ResponseResult;
import com.chinasoft.reposearch.entity.dto.SearchResultDTO;
import com.chinasoft.reposearch.entity.po.ElasticRequestParams;
import com.chinasoft.reposearch.entity.po.Repo;
import com.chinasoft.reposearch.service.ElasticService;
import com.chinasoft.reposearch.util.JacksonUtil;
import com.google.gson.Gson;
import org.codehaus.jackson.JsonParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
public class SearchController {
    private final ElasticService elasticService;

    @Autowired
    public SearchController(ElasticService elasticService) {
        this.elasticService = elasticService;
    }

    @GetMapping("/search")
    public Map<String, Object> search(ElasticRequestParams params) {
        Gson gson = new Gson();
        SearchResultDTO searchResultDTO = elasticService.searchDataList(params);
        List<String> repoJsons = searchResultDTO.getData();
        List<Repo> repos = repoJsons.stream().map((json) -> {
            Map<String, Object> map = gson.fromJson(json, Map.class);
            Repo repo = new Repo();
            repo.setOwner((String) map.get("owner"));
            repo.setName((String) map.get("name"));
            repo.setStars((((Number) map.get("stars")).longValue()));
            repo.setForks(((Number) map.get("forks")).longValue());
            repo.setWatchers(((Number) map.get("watchers")).longValue());
            repo.setIsFork((Boolean) map.get("isfork"));
            repo.setLanguages((List<Repo.Language>) map.get("languages"));
            repo.setLanguageCount(((Number) map.get("languagecount")).longValue());
            repo.setTopics((List<Repo.Topic>) map.get("topics"));
            repo.setTopicCount(((Number) map.get("topiccount")).longValue());
            repo.setDescription((String) map.get("description"));
            repo.setPrimaryLanguage((String) map.get("primarylanguage"));
            repo.setCreatedAt((String) map.get("createdat"));
            repo.setPushedAt((String) map.get("pushedat"));
            return repo;
        }).toList();
        Map<String, Object> result = new HashMap<>();
        result.put("page", params.getPage());
        result.put("size", repos.size());
        result.put("data", repos);
        result.put("total", searchResultDTO.getTotal());
        return result;
    }
}

